var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;


layui.use(["excel"], function () {
    let layer = layui.layer,
        excel = layui.excel;

    lay('.starttime').each(function(){
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el,name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon:true,
                indent: 20,
                expandedKeys:false
            },
            height: 'auto',
            data: data,
            on: function ({ arr, change, isAdd }) {
                return this
            }
        })
    }

    function getAllCostName(jsons) {
        let tmpitem=[]
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["feeCode"];
            tmparr["name"]=item["feeName"];
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }
    let operationList=[];
    let billNoStatusList = [];
    let allCostCodesList=[];
    let deptOperationList=[];
    layer.ready(function () {
        //获取币种
        $.ajax({
            url:"receivePayment/getCurrencyInfo",
            success:function(data){
                if(data.status == 200){
                    for(let i in data.data){
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();
        if(treeList && treeList.list){
            let userTree = getAllJson(treeList.list);
            operationList=getxmselect("#operationCode","operationCode", userTree);
        }else {
            operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        }

        //单据信息
        let billNoStatus = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2"},
            {name: "已批箱", value: "3"},
            {name: "完成箱", value: "4"},
            {name: "垃圾箱", value: "5"}
        ];
        billNoStatusList = getxmselect("#status", "status", billNoStatus);
        //费用类型
        let LxAndTypej={};
        LxAndTypej['type']=5;
        LxAndTypej['lx']=43;
        $.ajax({
            url:'cost/getCostName',
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(LxAndTypej),
            async:false,
            success:function(data){
                if(data.status==200){
                    let allCostCodes=getAllCostName(data.data);
                    allCostCodesList=getxmselect("#allCostCode", "allCostCode", allCostCodes);
                }
            }
        })

    });
    form.render();//表单刷新
    let initData = [];
    table.render({
        elem: '#cost2Select'
        ,data:initData
        ,toolbar: '#cost2Toolbar'
        ,totalRow: true
        ,cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'}
            ,{field:'code', title:'登记编号',sort:true,align:'center',width: 120}
            ,{field:'payeeName', title:'收款单位',sort:true,align:'center',width: 120}
            ,{field:'currencyName', title:'币种',sort:true,align:'center',width: 120}
            ,{field:'rmbRate', title:'RMB汇率',sort:true,align:'center',width: 120}
            ,{field:'usdRate', title:'USD汇率',sort:true,align:'center',width: 120}
            ,{field:'operatorName', title:'费用操作员',sort:true,align:'center',width: 120}
            ,{field:'status', title:'单据类型',sort:true,width: 120,align:'center'}
            ,{field:'costType', title:'费用类型',sort:true,width: 120,align:'center'}
            ,{field:'createTimeStr', title:'登记日期',sort:true,width: 120,align:'center'}
            ,{field:'totalCostCreateTimeStr', title:'实付日期',width: 120,sort:true,align:'center'},
            {field: 'exportContractCode', width: 120, title: '外销合同号',sort:true,align:'center'},
            {field:'stockCode', title:'采购合同号',sort:true,width: 120,align:'center'},
            {field: 'feeName',  title: '费用名称',width: 120,align:'center'}
            ,{field:'description', title:'备注',width: 120,align:'center'}
            ,{field:'totalAmount', title:'总金额',sort:true,width: 120,align:'center', totalRow: true}
            ,{field:'paymentCost', title:'实付金额',sort:true,width: 120,align:'center', totalRow: true}
            ,{field:'unPaymentCost', title:'未付金额',sort:true,width: 120,align:'center', totalRow: true}
            ,{field:'costPaymentType', title:'支付情况',sort:true,width: 120,align:'center'}
            ,{field:'billCompanyName', title:'制单公司',sort:true,width: 120,align:'center'}
        ]]
        ,id: 'maininformationtableid'
        ,height: $(document).height() - $('#cost2Select').offset().top - 75,
        //开启分页
        page: true,
        limits: [300,600,900],
    });

//字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //搜索提交
    form.on('submit(submitform)', function(data){
        if (isEmpty(operationList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) ){
            data.field.operationCode=user.code;
        }

        table.reload('maininformationtableid', {
            page: {
                limit:300,
                curr: 1
            },
            url:'cost/costStatistics2ListByPage',
            where:  data.field
        }, 'data');
        return false;
    });


    form.on('submit(costExcel)', function (data) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: data.field,
            url:'cost/costStatistics2Export',
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 120,
                        'AJ': 120
                    }, 120);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '费用支付统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });

    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        billNoStatusList.setValue([ ]);
        allCostCodesList.setValue([ ]);
        deptOperationList.setValue([ ]);
    };
});
